package com.service.impl;

import com.dao.AccountDao;
import com.dao.OrdersDao;
import com.dao.RoomDao;
import com.dao.RoomTypeDao;
import com.pojo.Account;
import com.pojo.Order;
import com.pojo.Room;
import com.pojo.RoomType;
import com.service.OrdersService;
import com.util.UUIDUtils;
import com.vo.OrdersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.Date;
import java.util.List;

/**
 * @author mornd
 * @date 2020/12/1 - 15:03
 */
@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private RoomDao roomDao;
    @Autowired
    private RoomTypeDao roomTypeDao;
    /**
     * 添加订单
     *
     * @param order
     * @return
     */
    @Override
    public int addOrders(Principal principal,Order order) {
        //补全订单信息
        //添加订单编号
        order.setOrdersNo(UUIDUtils.randomID());
        //添加预定的用户id
        Account account = accountDao.simpleFindById(principal.getName());
        order.setAccountId(accountDao.simpleFindById(principal.getName()).getId());
        //添加状态 1为待确认 2为已确认
        order.setStatus(1);
        //添加订单提交日期
        order.setReserveDate(new Date());
        int count = ordersDao.addOrders(order);
        if(count > 0){
            //添加房型id
            RoomType roomTypeById = roomTypeDao.findRoomTypeById(order.getRoomTypeId());
            roomTypeById.setAvilableNum(roomTypeById.getAvilableNum() - 1);//可用房间数减1
            roomTypeById.setReservedNum(roomTypeById.getReservedNum() + 1);
            roomTypeDao.updateRoomType(roomTypeById);
            //修改房间信息
            Room roomById = roomDao.findRoomById(order.getRoomId());
            roomById.setStatus(2);//2表示已预定
            roomDao.updateRoom(roomById);

        }
        return count;
    }

    /**
     * 查询订单集合
     *
     * @param ordersVo
     * @return
     */
    @Override
    public List<Order> findOrderList(OrdersVo ordersVo) {
        return ordersDao.findOrderList(ordersVo);
    }

    /**
     * 确认订单
     *
     * @param ids
     * @return
     */
    @Override
    public boolean confirmOrders(List<Integer> ids) {
        try {
            ordersDao.confirmOrders(ids);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
